﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Main
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// triggers login process, if the user exists and is NOT admin, it becomes limited user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text != String.Empty && txtPassword.Text != String.Empty)
            {
                TechnoStoreMainDataContext db = new TechnoStoreMainDataContext();
                User user = new User();

                if(txtUsername.Text == "admin")
                    user = db.Users.Where(u => u.email == txtUsername.Text && u.password == txtPassword.Text).SingleOrDefault();
                else
                    user = db.Users.Where(u => u.email == txtUsername.Text && u.password == ControlCommon.getMd5Hash(txtPassword.Text)).SingleOrDefault();

                if (user != null)
                {

                    Session["ID"] = user.ID;
                    Session["UserName"] = user.email;
                    Session["Company"] = user.company;
                    if (user.isadmin == false)
                    {
                        Session["LIMITEDUSER"] = "true";
                        Response.Redirect("Default.aspx");
                    }
                    else
                    {
                        Response.Redirect("Default.aspx");
                    }
                }
                else
                {
                    txtUsername.BorderColor = System.Drawing.Color.Red;
                    txtUsername.BorderWidth = 1;
                    txtUsername.BorderStyle = BorderStyle.Solid;
                    txtPassword.BorderColor = System.Drawing.Color.Red;
                    txtPassword.BorderWidth = 1;
                    txtPassword.BorderStyle = BorderStyle.Solid;
                }
            }
            else
            {
                txtUsername.BorderColor = System.Drawing.Color.Red;
                txtUsername.BorderWidth = 1;
                txtUsername.BorderStyle = BorderStyle.Solid;
                txtPassword.BorderColor = System.Drawing.Color.Red;
                txtPassword.BorderWidth = 1;
                txtPassword.BorderStyle = BorderStyle.Solid;
            }
        }

        protected void btnSignUp_Click(object sender, EventArgs e)
        {
            Response.Redirect("Signup.aspx");
        }
    }
}